package com.hylu.springcloud.service.impl;

import com.hylu.springcloud.entity.Book;
import com.hylu.springcloud.service.BookInterface;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 可以通过两种方式实现ES调用
 * <p>
 * 方法一：ElasticsearchRestTemplate
 */
@Service
public class BookTemplateService implements BookInterface {

    @Autowired
    private ElasticsearchRestTemplate esRestTemplate;

    @Override
    public Book saveBook(Book book) {
        return esRestTemplate.save(book);
    }

    @Override
    public void updateBookTitle(String id, String title) {
        Document doc = Document.create();
        doc.put("title",title);
        doc.put("updateTime",new Date());
        UpdateQuery.Builder builder = UpdateQuery.builder(id).withDocument(doc);
        UpdateQuery updateQuery = builder.build();
        UpdateResponse updateResponse = esRestTemplate.update(updateQuery, IndexCoordinates.of("book"));
        System.out.println(updateResponse.getResult());
    }


    public SearchHits<Book> queryBook(String title){
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
        searchQueryBuilder.withFields("title",title);
        SearchHits<Book> search = esRestTemplate.search(searchQueryBuilder.build(), Book.class);
        return search;
    }


}
